package com.shxy.cloudclassroom.controller.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shxy.cloudclassroom.entity.pojo.Assignment;
import com.shxy.cloudclassroom.entity.pojo.AssignmentSubmission;
import com.shxy.cloudclassroom.entity.pojo.Major;
import com.shxy.cloudclassroom.entity.pojo.User;
import com.shxy.cloudclassroom.entity.vo.AssignmentDetailVO;
import com.shxy.cloudclassroom.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static com.shxy.cloudclassroom.utils.SystemConstant.*;

/**
 * @Author 吴汇明
 * @School 绥化学院
 * @CreateTime 2025.10.17
 * 作业考试模块
 */
@Controller
@RequestMapping("/assignment")
public class AssignmentController {

    @Resource
    private AssignmentService assignmentService;

    @Resource
    private MajorService majorService;

    /**
     * 作业列表页面
     */
    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size,
                       Model model) {
        Page<Assignment> assignmentPage = new Page<>(page, size);
        LambdaQueryWrapper<Assignment> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Assignment::getDeadline);
        List<Assignment> assignmentList = assignmentService.getAssignmentList(assignmentPage, wrapper);
        model.addAttribute(ASSIGNMENT_LIST, assignmentList);
        model.addAttribute(HELPER_PAGE, assignmentPage);
        return "/assignment/list";
    }

    /**
     * 发布作业页面
     */
    @GetMapping("/publish")
    public String publishPage(Model model) {
        List<Major> majorList = majorService.query().list();
        model.addAttribute(MAJOR_LIST, majorList);
        return "assignment/publish";
    }

    /**
     * 发布作业
     */
    @PostMapping("/publish")
    public String publishAssignment(Assignment assignment,
                                    @RequestParam(value = "file", required = false) MultipartFile file,
                                    HttpSession session) {
        Map<String, Object> result = assignmentService.publishAssignment(assignment, file, session);
        if (!(boolean) result.get("success")) {
            if (result.containsKey("redirect")) {
                return (String) result.get("redirect");
            }
        }
        return (String) result.getOrDefault("redirect", "redirect:/assignment/list");
    }

    /**
     * 提交作业页面
     */
    @GetMapping("/submit/{id}")
    public String submitPage(@PathVariable Integer id, Model model, HttpSession session) {
        //校验用户是否过期
        User user = (User) session.getAttribute(LOGIN_USER);
        if (user == null) {
            return "redirect:/login";
        }
        Assignment assignment = assignmentService.getById(id);
        //当前时间大于截止时间结果为负数,说明还没有结束
        int result = assignment.getDeadline().compareTo(LocalDateTime.now());
        if (result < 0) {
            return "redirect:/assignment/list";
        }
        model.addAttribute(ASSIGNMENT_SINGLETON, assignment);
        return "/assignment/submit";
    }

    /**
     * 提交作业
     */
    @PostMapping("/submit")
    public String submitAssignment(AssignmentSubmission submission,
                                   @RequestParam("file") MultipartFile file,
                                   HttpSession session,
                                   RedirectAttributes redirectAttributes) {
        Map<String, Object> result = assignmentService.submitAssignment(submission, file, session);
        if (!(boolean) result.get("success")) {
            if (result.containsKey("redirect")) {
                return (String) result.get("redirect");
            }
            redirectAttributes.addFlashAttribute(SUBMISSION_MESSAGE, result.get("message"));
        } else {
            redirectAttributes.addFlashAttribute(SUBMISSION_MESSAGE, result.get("message"));
        }
        return "redirect:/assignment/list";
    }

    /**
     * 查看作业详情
     */
    @GetMapping("/{id}")
    public String detail(@PathVariable Integer id, Model model, HttpSession session) {
        AssignmentDetailVO assignmentDetailVO = assignmentService.getAssignmentDetail(id, session);
        if (assignmentDetailVO == null) {
            return "redirect:/assignment/list";
        }
        
        model.addAttribute(ASSIGNMENT_SUBMISSION, assignmentDetailVO.getAssignmentSubmission());
        model.addAttribute(MAJOR, assignmentDetailVO);
        model.addAttribute(ASSIGNMENT_SINGLETON, assignmentDetailVO);
        
        // 如果是管理员，添加额外信息
        if (assignmentDetailVO.getSubmissions() != null) {
            model.addAttribute("submissions", assignmentDetailVO.getSubmissions());
        }
        if (assignmentDetailVO.getUserMap() != null) {
            model.addAttribute(USER_MAP, assignmentDetailVO.getUserMap());
        }
        
        return "assignment/detail";
    }

}